﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace ChangeWifiWebApi.Accessors
{
  public class NetworkAdapterAccessor
  {
    public static readonly string[] DNSServerSearchOrder = new[] { "10.4.246.1", "8.8.8.8" };

    /// <summary>
    /// 设置本机为静态ip模式
    /// </summary>
    /// <param name="dns">0：DNS 1：备用DNS</param>
    /// <param name="ip">静态ip</param>
    /// <param name="mask">掩码</param>
    /// <param name="gateWay">网关</param>
    public void SetStaticIp(string[] dns
      , string ip = "192.168.191.2"
        , string mask = "255.255.255.0"
        , string gateWay = "192.168.191.1")
    {
      ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection moc = wmi.GetInstances();
      ManagementBaseObject inPar = null;
      ManagementBaseObject outPar = null;

      var mo = moc.Cast<ManagementObject>()
        .First(dd => (bool)dd["IPEnabled"]);

      //设置IP地址和子网掩码 
      inPar = mo.GetMethodParameters("EnableStatic");
      inPar["IPAddress"] =      new [] { ip };
      inPar["SubnetMask"] = new [] {mask };
      outPar = mo.InvokeMethod("EnableStatic", inPar, null);
      //设置网关地址  
      inPar = mo.GetMethodParameters("SetGateways");
      inPar["DefaultIPGateway"] = new [] { gateWay};
      outPar = mo.InvokeMethod("SetGateways", inPar, null);
      //设置DNS  
      inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
      inPar["DNSServerSearchOrder"] = dns; // 1.DNS 2.备用DNS  
      outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
    }

    /// <summary>
    /// 设置本机为自动获取ip模式
    /// </summary>
    public void SetAutoGetIp()
    {
      ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection moc = wmi.GetInstances();
    
      foreach (ManagementObject mo in moc)
      {
        if (!(bool)mo["IPEnabled"])
          continue;
        mo.InvokeMethod("SetDNSServerSearchOrder", null);
        mo.InvokeMethod("EnableDHCP", null);
      }
    }
  }
}
